<template>

  <!-- 搜索框 -->
  <el-card style="height: 80px">
    <el-form :model="queryForm" :inline="true" class="form">
      <el-form-item label="姓名:">
        <el-input
            v-model="queryForm.queryName"
            placeholder="请输入姓名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>


  <!-- 添加用户和批量删除 -->
  <el-card style="margin: 10px 0">
    <el-tooltip effect="dark" content="添加" placement="top">
      <el-button
          type="success"
          size="default"
          icon="Plus"
          @click="handleAdd"
      >
      </el-button>
    </el-tooltip>
    <!-- table展示用户信息 -->
    <el-table
        style="margin: 10px 0"
        border
        :data="userTableData"
    >
      <el-table-column
          label="姓名"
          align="center"
          prop="name"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="电话"
          align="center"
          prop="phone"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="邮箱"
          align="center"
          prop="email"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="地址"
          align="center"
          prop="address"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="账号"
          align="center"
          prop="username"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="性别"
          align="center"
          prop="gender"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="余额"
          align="center"
          prop="accountBalance"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="头像"
          align="center"
          prop="avatar"
          show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-image style="width: 100px; height: 100px;" :preview-src-list="[row.avatar]" :src="row.avatar"
                    fit="cover"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120px" align="center">
        <template #="{ row }">
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEdit(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(row.userId)"
            >
            </el-button>
          </el-tooltip>
        </template>

      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findAll"
        @size-change="handler"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" size="1000px">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ trainersForm.userId ? '更新' : '添加' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="trainersForm" :rules="rules" ref="formRef">
        <el-form-item label="姓名" prop="name">
          <el-input
              placeholder="请您输入姓名"
              v-model="trainersForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
              placeholder="请您输电话"
              v-model="trainersForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              type="email"
              placeholder="请您输邮箱"
              v-model="trainersForm.email"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              placeholder="请您输地址"
              v-model="trainersForm.address"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input
              :disabled="trainersForm.userId"
              placeholder="请您输账号"
              v-model="trainersForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-switch
              v-model="sex"
              inline-prompt
              active-text="男"
              inactive-text="女"
          />
        </el-form-item>
        <el-form-item label="余额" prop="accountBalance">
          <el-input
              v-model="trainersForm.accountBalance"
              style="width: 240px"
              placeholder="Please input"
              :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
          />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg,.gif"
              drag
              :before-upload="handleBeforeUpload"
              :http-request="handleCustomUploadAvatar"
              multiple
          >
            <img style="width: 200px; height: 200px;" v-if="trainersForm.avatar"
                 :src="trainersForm.avatar" class="avatar" alt="图片"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>


</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick} from 'vue'
import {ElFormItem, ElMessage, ElMessageBox} from 'element-plus'
import {Plus} from "@element-plus/icons-vue";
import {apiGet, apiPost} from "@/utils/api.ts";
// 表单数据
let trainersForm = reactive(
    {
      userId: 0,
      name: '',
      phone: '',
      email: '',
      address: '',
      username: '',
      gender: '男',
      accountBalance: 0.00,
      avatar: '',
    })
//搜索表单数据
let queryForm = reactive({
  queryName: '',
})
//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)
//总个数
let total = ref<number>(0)
//存储全部用户的数组
let userTableData = ref([])
//定义响应式数据控制抽屉的显示与隐藏 添加用户和修改用户
let drawer = ref<boolean>(false)
//获取form组件实例
let formRef = ref<any>()
let sex = ref<boolean>(false);
//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value,
    name: queryForm.queryName
  }
  //获取表单数据
  let {data} = await apiGet('/users/findAll', parameter)
  total.value = data.count
  userTableData.value = data.data
}

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll()
}

//搜索按钮的回调
const search = () => {
  findAll()
}

//添加用户按钮的回调
const handleAdd = () => {
  //抽屉显示出来
  drawer.value = true
  sex.value = false;
  //清空userParams的数据以及userParams继承User里面的所有数据
  Object.assign(trainersForm, {
    userId: 0,
    name: '',
    phone: '',
    email: '',
    address: '',
    username: '',
    gender: '男',
    accountBalance: 0.00,
    role: 2,
    level: 1,
    state: 1,
    specialties: '',
    certifications: '',
    avatar: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//更新用户按钮的回调
const handleEdit = (row: any) => {
  row.gender === '男' ? sex.value = true : sex.value = false;
  //抽屉显示出来
  drawer.value = true
  //将用户的信息赋值给userParams
  Object.assign(trainersForm, {
    ...row
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()
  if (!sex.value) {
    trainersForm.gender = '女';
  } else {
    trainersForm.gender = '男';
  }
  //保存按钮:添加新的用户|更新已有的用户账号信息
  trainersForm.userId ? await apiPost('/users/edit', {...trainersForm}) : await apiPost('/users/add', {...trainersForm})
  await findAll()
  drawer.value = false
}

//删除
const handleDelete = async (userId: number) => {
  //提示用户确认删除吗
  ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        await apiPost('/users/delete', {userId})
        await findAll(userTableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
      })
      .catch(() => {
      })
}

//上传文件之前做的一些判断
const handleBeforeUpload = (file) => {
  // 检查文件类型 只能上传.png,.jpg,.jpeg,.gif
  const isExcel = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif';
  if (!isExcel) {
    ElMessage.error('上传文件只能是.png,.jpg,.jpeg,.gif 格式!');
    return false;
  }

  //上传文件大小不能超过20M
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error('上传文件大小不能超过 20MB!');
    return false;
  }
  return isExcel && isLt20M;
};
const handleCustomUploadAvatar = async (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  let {msg} = await apiPost('/upload/img', formData, {headers: {'Content-Type': 'multipart/form-data'}});
  trainersForm.avatar = msg;
};
const validatorName = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'));
  } else {
    callback();
  }
}
const validatorEmail = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入邮箱'));
  } else {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
      callback(new Error('请输入正确的邮箱'));
    }
    callback();
  }
}
const validatorAccount = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'));
  } else {
    callback();
  }
}
//表单校验的规则对象
const rules = {
  name: [{required: true, trigger: 'blur', validator: validatorName}],
  email: [{required: true, trigger: 'blur', validator: validatorEmail}],
  username: [{required: true, trigger: 'blur', validator: validatorAccount}],
}


//组件挂载完毕
onMounted(() => {
  findAll()
})
</script>

<style scoped>
</style>
